package com.tianji.promotion.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.domain.po.ExchangeCode;
import com.tianji.promotion.mapper.ExchangeCodeMapper;
import com.tianji.promotion.service.IExchangeCodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.promotion.utils.CodeUtil;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static com.tianji.promotion.constants.PromotionConstants.COUPON_CODE_MAP_KEY;
import static com.tianji.promotion.constants.PromotionConstants.COUPON_CODE_SERIAL_KEY;

/**
 * <p>
 * 兑换码 服务实现类
 * </p>
 *
 * @author xioayang
 * @since 2024-07-03
 */
@Service
public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, ExchangeCode> implements IExchangeCodeService {
    private final StringRedisTemplate redisTemplate;
    private final BoundValueOperations<String, String> serialOps;

    public ExchangeCodeServiceImpl(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.serialOps = redisTemplate.boundValueOps(COUPON_CODE_SERIAL_KEY);
    }

    /**
     * 异步生成兑换码
     *
     * @param coupon 优惠券
     */
    @Override
    @Transactional
    @Async("generateExchangeCodeExecutor")
    public void asyncGenerateCode(Coupon coupon) {
        // 发放数量
        Integer totalNum = coupon.getTotalNum();
        // 1.获取Redis自增序列号
        Long result = serialOps.increment(totalNum);
        try {
            if (result == null) {
                return;
            }
            int maxSerialNum = result.intValue();
            List<ExchangeCode> list = new ArrayList<>(totalNum);
            for (int serialNum = maxSerialNum - totalNum + 1; serialNum <= maxSerialNum; serialNum++) {
                // 2.生成兑换码
                String code = CodeUtil.generateCode(serialNum, coupon.getId());
                ExchangeCode e = new ExchangeCode();
                e.setCode(code);
                e.setId(serialNum);
                e.setExchangeTargetId(coupon.getId());
                e.setExpiredTime(coupon.getIssueEndTime());
                list.add(e);
            }
            // 3.保存数据库
            saveBatch(list);
        } catch (Exception e) {
            if (ObjectUtil.isNotEmpty(result)) {
                serialOps.decrement(totalNum);
            }
            e.printStackTrace();
            throw new BizIllegalException("");
        }
    }

    @Override
    public boolean updateExchangeMark(long serialNum, boolean mark) {
        Boolean boo = redisTemplate.opsForValue().setBit(COUPON_CODE_MAP_KEY, serialNum, mark);

        return boo != null && boo;
    }
}
